<template>
  <div class="traffic-chart"
    :id="dId ? dId:'ringChart'"></div>
</template>
<script>
export default {
  name: 'RingChart',
  props: {
    chartData: {
      type: Object,
      default: () => {},
    },

    dId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      myRingChart: null,
    }
  },
  watch: {
    chartData: {
      deep: true,
      immediate: true,
      handler(val) {
        if (val && JSON.stringify(val) !== '{}') {
          this.$nextTick(() => {
            this.ringChart()
          })
        }
      },
    },
  },
  mounted() {
    window.addEventListener('resize', this.resizeHandler)
  },
  methods: {
    ringChart() {
      this.myRingChart = this.$echarts.init(
        document.getElementById(`${this.dId ? this.dId : 'ringChart'}`)
      )

      var data = []
      let total = 0
      if(this.chartData && this.chartData.data && Array.isArray(this.chartData.data)) {
        this.chartData.data.forEach((item) => {
          data.push({ name: item.label, value: item.value })
          total = total + item.value
        })
      }

      //求余error优化
      if (!total) {
        total = 1
      }

      let that = this

      let option = {
        legend: {
          show: false,
        },
        color: this.chartData.colors,
        series: [
          {
            type: 'pie',
            radius: ['40%', '55%'],
            center: ['50%', '50%'],
            label: {
              formatter: (params) => {
                return `${params.name}：${(
                  (params.value / total) *
                  100
                ).toFixed(2)}%`
              },
              rich: {},
            },
            labelLine: {
              show: false,
            },
            data: data,
          },
        ],
      }
      this.myRingChart.setOption(option)
    },
    resizeHandler() {
      if (this.myRingChart) {
        this.myRingChart.resize()
      }
    },
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeHandler)
    if (!this.myRingChart) {
      return
    }
    this.myRingChart.dispose()
    this.myRingChart = null
  },
}
</script>
<style lang="scss" scoped>
.traffic-chart {
  height: 310px;
  margin-top: 30px;
}
</style>
